import requests
import json

class GdhsParseJsonTask:
    def get_stock_by_interface(stocknum):
        url = 'https://datacenter-web.eastmoney.com/api/data/v1/get'
        headers = {
            "Accept": "*/*",
            "Accept-Encoding": "gzip, deflate, br",
            "Accept-Language": "zh-CN,zh;q=0.9",
            "cache-control": "no-cache",
            "Connection": "keep-alive",
            "Host": "datacenter-web.eastmoney.com",
            "Referer": "https://data.eastmoney.com/",
            "sec-ch-ua": '"Google Chrome";v="89", "Chromium";v="89", ";Not A Brand";v="99"',
            "sec-ch-ua-mobile": '?0',
            "Sec-Fetch-Dest": "script",
            "Sec-Fetch-Mode": "no-cors",
            "Sec-Fetch-Site": "same-origin",
            "User-Agent": "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36",
            "X-Requested-With": "XMLHttpRequest",
        }

        params = {
            "sortColumns": "END_DATE",
            "sortTypes": "-1",
            "pageSize": 150,
            "pageNumber": 1,
            "reportName": "RPT_HOLDERNUM_DET",
            "columns": "SECURITY_CODE,SECURITY_NAME_ABBR,END_DATE,HOLDER_NUM,AVG_HOLD_NUM,TOTAL_MARKET_CAP,HOLD_NOTICE_DATE",
            "quoteColumns": "f2,f3",
            "filter": "(SECURITY_CODE=\"{}\")".format(stocknum),
            "source": "WEB",
            "client": "WEB"
        }

        res = requests.get(url, headers=headers, params=params, verify=False)
        data = json.loads(res.text)
        results = []
        if 'result' in data and data['result'] is not None:
            datas = data['result']['data']
            for row in datas:
                code = row['SECURITY_CODE']
                name = row['SECURITY_NAME_ABBR']
                end_date = row['END_DATE']
                gds = row['HOLDER_NUM']
                avg_num = row['AVG_HOLD_NUM']
                if avg_num is None:
                    avg_num = ''
                total = row['TOTAL_MARKET_CAP'] #总市值
                if total is None:
                    break
                update_date = row['HOLD_NOTICE_DATE']

                lineData = [code, name, end_date, gds
                    , avg_num, total, update_date]
                results.append(lineData)
        else:
            print("{} not found".format(stocknum))
        return results
